using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using ApiTest.Api.Entity;
using System.Linq;
using ApiTest.Api.Db;
using ApiTest.Api.Repository;
using ApiTest.Api.Params;
using Microsoft.Extensions.Configuration;
using ApiTest.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Admin3000.Backend.Api.Params;

namespace ApiTest.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;
        private TokenParameter _tokenParameter;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        



        [HttpGet]
        public dynamic Get()
        {   
            var pageIndex=int.Parse(Request.Query["pageIndex"][0]);
            var pageSize=int.Parse(Request.Query["pageSize"][0]);

            var user = _usersRepository.Table;
            var u=user.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();
            var res= new
            {
                Code = 1000,
                Data = new{Data =u,Pager=new{pageIndex,pageSize,rowsTotal=user.Count()}},
                Msg = "获取用户列表成功"
            };
            return JsonHelper.Serialize(res);
        }
        
        [HttpGet("content/{Content}"),Route("content")]
        public dynamic GetName(string Content)
        {
            var pageIndex=int.Parse(Request.Query["pageIndex"][0]);
            var pageSize=int.Parse(Request.Query["pageSize"][0]);
            var user=_usersRepository.Table.Where(x=>x.Username.Contains(Content));
            var u=user.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();
             return JsonHelper.Serialize (new
            {
                Code = 1000,
                Data = new{Data =u,Pager=new{pageIndex,pageSize,rowsTotal=user.Count()}},
                Msg = "模糊查询成功"
            });
        }
        

        [HttpGet("{id}")]
        public dynamic Get(int id)

        {
            
            var user = _usersRepository.GetById(id);

            return JsonHelper.Serialize (new
            {
                Code = 1000,
                Data = user,
                Msg = "查询指定用户成功"
            });
        }
        
        [HttpPost]
        public dynamic Post(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password==null?"123": newUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return JsonHelper.Serialize (new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空"
                });
            }
            var user = new Users
            {
                Username = newUser.Username,
                Password = newUser.Password,
                Remarks  = newUser.Remarks,
                // IsActived= newUser.IsActived
            };
            _usersRepository.Insert(user);
            return JsonHelper.Serialize (new
            {
                Code = 1000,
                Data = user,
                Msg = "添加用户成功"
            });
        }
        [HttpPut("{id}")]
        public dynamic Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username.Trim();
            var password = updateUser.Password.Trim();

            

            
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return JsonHelper.Serialize (new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空"
                });
            }

            var user = _usersRepository.GetById(id);
            if (user == null)
            {
                return JsonHelper.Serialize (new
                {
                    Code = 104,
                    Data = "",
                    Msg = "查询不到该用户，无法更新，请重试"
                });
            }

            user.Username = updateUser.Username;
            user.Password = updateUser.Password;
            user.Remarks  = updateUser.Remarks;
            // user.IsActived= updateUser.IsActived;

            _usersRepository.Update(user);

            return JsonHelper.Serialize (new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            });


        }

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            _usersRepository.Delete(id);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除成功"
            };


        }

        [AllowAnonymous]
        [HttpPost,Route("token")]
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user = _usersRepository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();
            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token = TokenHelper.GenerateToken(_tokenParameter, user.Username);
             var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token ,refreshToken = refreshToken},
                Msg = "登录成功"
            };
        }
        
        //  [AllowAnonymous]
        [HttpPost, Route("refreshtoken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {
            
                var username=TokenHelper.ValidateToken(_tokenParameter,refresh);

                if (string.IsNullOrEmpty(username))
                {
                    return new
                    {
                        Code = 1002,
                        Data = "",
                        Msg = "token验证失败"
                    };
                }

                var token = TokenHelper.GenerateToken(_tokenParameter, username);
                var refreshToken = "112358";


                return new
                {
                    Code = 1000,
                    Data = new { Token = token, refreshToken = refreshToken },
                    Msg = "刷新token成功^_^"
                };
            }

    }
}